package com.ttmall.common.utils;

import org.apache.log4j.Logger;

import java.io.*;

/**
 * Created by GalaIO on 2018/1/14.
 */
public class FileSaveUtil {

    private static Logger logger = Logger.getLogger(FileSaveUtil.class);

    private static int FILE_SAVING_SIZE = 1024;

    public static boolean savePic(InputStream inputStream, String fileName, String path) {
        boolean isFinish = true;
        OutputStream os = null;
        try {
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[FILE_SAVING_SIZE];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件

            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }

        } catch (IOException e) {
            logger.error(e.getMessage());
            isFinish = false;
        } catch (Exception e) {
            logger.error(e.getMessage());
            isFinish = false;
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return isFinish;
    }


    public static boolean savePic(byte[] byteArr, String fileName, String path) {
        boolean isFinish = true;
        OutputStream os = null;
        try {
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            os.write(byteArr);

        } catch (IOException e) {
            logger.error(e.getMessage());
            isFinish = false;
        } catch (Exception e) {
            logger.error(e.getMessage());
            isFinish = false;
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return isFinish;
    }
}
